package com.macro.mall.controller;

import com.macro.mall.annotationUtil.CurrentUserName;
import com.macro.mall.common.api.CommonPage;
import com.macro.mall.common.api.CommonResult;
import com.macro.mall.common.api.ResultCode;
import com.macro.mall.common.util.DateUtil;
import com.macro.mall.common.util.HttpClient;
import com.macro.mall.dao.DistributionOrderDao;
import com.macro.mall.dao.PortalOrderDao;
import com.macro.mall.dao.WithdrawalApplyDao;
import com.macro.mall.domain.AgentSkuListResult;
import com.macro.mall.dto.FilterParam;
import com.macro.mall.dto.OmsOrderQueryParam;
import com.macro.mall.dto.UmsWithdrawalApplyDto;
import com.macro.mall.mapper.UmsAgentCoordMapper;
import com.macro.mall.mapper.UmsMemberMapper;
import com.macro.mall.model.*;
import com.macro.mall.service.UmsAdminService;
import com.macro.mall.service.UmsDistributionMemberService;
import com.macro.mall.service.UmsMemberService;
import com.macro.mall.service.UmsWithdrawalApplyService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import local.com.quyum.aliyun.aliyunsms.service.ISmsService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 分销管理
 *
 * @author zhouboyu
 * @Date 2020年8月27日
 */
@Controller
@Api(tags = "OmsDistributionController", description = "分销管理")
@RequestMapping("/distribution")
public class OmsDistributionController {
    @Autowired
    private UmsDistributionMemberService umsDistributionMemberService;
    @Autowired
    private UmsAdminService umsAdminService;
    @Autowired
    private ISmsService smsService;
    @Autowired
    private UmsMemberMapper umsMemberMapper;
    @Autowired
    private UmsMemberService memberService;
    @Autowired
    private UmsWithdrawalApplyService withdrawalApplyService;

    @Autowired
    private PortalOrderDao portalOrderDao;
    @Autowired
    private DistributionOrderDao distributionOrderDao;
    @Autowired
    private WithdrawalApplyDao withdrawalApplyDao;
    @Autowired
    private UmsAgentCoordMapper coordMapper;


    /**
     * 获取当前门店用户的分销商
     *
     * @return
     * @author zhouboyu
     * @Date 2020年8月27日
     */
    @ApiOperation("查询自己的分销商")
    @RequestMapping(value = "/member/list", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<CommonPage<OmsQueryDistributionResult>> list(@CurrentUserName String userName, @RequestBody OmsOrderQueryParam queryParam) {
        UmsAdmin adminByUsername = this.umsAdminService.getAdminByUsername(userName);
        List<UmsMember> list = this.umsDistributionMemberService.list(adminByUsername.getId(), queryParam.getPageNum(), queryParam.getPageSize(), queryParam.getRealName(), queryParam.getPhone(),1);
        CommonPage<UmsMember> umsMemberCommonPage = CommonPage.restPage(list);
        List<UmsMember> members = umsMemberCommonPage.getList();
        List<OmsQueryDistributionResult> result = new ArrayList<>();
        members.forEach(p -> {
            OmsQueryDistributionResult queryDistributionResult = new OmsQueryDistributionResult();
            BeanUtils.copyProperties(p, queryDistributionResult);
            //获取当前分销商的佣金总额
            BigDecimal commission = distributionOrderDao.getTotalCommission(p.getId(), 3);
            queryDistributionResult.setCommission(commission);
            //获取当前分销商的已结算
            BigDecimal totalCommission = distributionOrderDao.getTotalCommission(p.getId(), 6);
            queryDistributionResult.setTotalCommission(totalCommission);
            //用户已经提现的总金额
            BigDecimal hasWithdrawalCommission = this.withdrawalApplyDao.getHasWithdrawalCommission(p.getId(), null, null);
            queryDistributionResult.setHasWithdrawalCommission(hasWithdrawalCommission);
            //查询本月业绩总额
            Date endDate = new Date();
            Date startDate = DateUtil.getFirstDayDateOfMonth(endDate);
            BigDecimal monthSales = portalOrderDao.getTotalAmount(p.getId(), startDate, endDate);
            queryDistributionResult.setMonthSales(monthSales);
            //查询定位信息,2020年10月9日add高强
            UmsAgentCoordExample coordExample = new UmsAgentCoordExample();
            coordExample.createCriteria().andAgentIdEqualTo(queryDistributionResult.getId()).andStoreIdEqualTo(queryDistributionResult.getStoreId());
            List<UmsAgentCoord> umsAgentCoords = coordMapper.selectByExample(coordExample);
            if (!CollectionUtils.isEmpty(umsAgentCoords)) {
                queryDistributionResult.setCoords(umsAgentCoords);
            }
            //end
            result.add(queryDistributionResult);
        });
        CommonPage<OmsQueryDistributionResult> resultCommonPage = new CommonPage<>();
        BeanUtils.copyProperties(umsMemberCommonPage, resultCommonPage);
        resultCommonPage.setList(result);
        return CommonResult.success(resultCommonPage);
    }

    /**
     * 门店创建自己的分销商
     *
     * @return
     * @author zhouboyu
     * @Date 2020年8月28日
     */
    @ApiOperation("门店创建自己的分销商")
    @RequestMapping(value = "/member/add", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult add(@CurrentUserName String userName, @RequestBody UmsMember umsMember) {
        return this.umsDistributionMemberService.addOrBindUser(userName, umsMember);
    }


    /**
     * 获取短信验证码
     */
    @ApiModelProperty("获取短信验证码")
    @RequestMapping(value = "/getVerifySms", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult getVerifySms(@RequestParam String mobile) {
        return this.smsService.sendRound6Sms(mobile);
    }


    /**
     * 验证用户输入的短信验证码是否正确，如果正确
     * 当用户输入的手机号已经注册时，返回手机号绑定的用户信息
     * 没有注册时，返回空对象
     *
     * @return
     * @author zhouboyu
     * @Date 2020年8月27日
     */
    @ApiOperation("校验短信验证码")
    @RequestMapping(value = "/member/verifySms", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<UmsMember> verifySms(@RequestParam String mobile, @RequestParam String smsVerifyCode) {
        CommonResult commonResult = this.smsService.verifyCode(mobile, smsVerifyCode);
        if (commonResult.getCode() == ResultCode.SUCCESS.getCode()) {
            UmsMemberExample umsMemberExample = new UmsMemberExample();
            umsMemberExample.createCriteria().andPhoneEqualTo(mobile);
            List<UmsMember> umsMembers = this.umsMemberMapper.selectByExample(umsMemberExample);
            if (!CollectionUtils.isEmpty(umsMembers)) {
                commonResult.setData(umsMembers.get(0));
            } else {
                commonResult.setData(null);
            }
        } else {
            commonResult.setData(null);
        }
        return commonResult;
    }

    /**
     * 修改分销员
     *
     * @param id
     * @param umsMember
     * @return
     * @author 高强
     * @Date 2020年9月4日
     */
    @ApiOperation("门店修改自己的分销商")
    @ResponseBody
    @RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
    public CommonResult updateDistributionMember(@PathVariable(value = "id") long id, @RequestBody UmsMember umsMember) {
        return memberService.updateDistributionMember(id, umsMember);
    }

    /**
     * 取消当前乡村经纪人与门店的关系
     *
     * @return
     * @author zhouboyu
     * @Date 2020年8月28日
     */
    @ApiOperation("取消当前乡村经纪人与门店的关系")
    @RequestMapping(value = "/member/cancel", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult cancel(Long memberId) {
        long count = this.umsDistributionMemberService.getMemberCountByDistributionId(memberId);
        if (count > 0l) {
            return CommonResult.failed("该乡村经纪人下有客户，不能直接删除");
        } else {
            UmsMember umsMember = this.umsMemberMapper.selectByPrimaryKey(memberId);
            umsMember.setAgentId(null);
            umsMember.setType(0);
            umsMember.setStoreUserId(null);
            umsMember.setStoreId(null);
            int i = this.umsMemberMapper.updateByPrimaryKey(umsMember);
            if (i > 0) {
                return CommonResult.success(i);
            } else {
                return CommonResult.failed("删除失败，请稍后再试");
            }
        }
    }

    /**
     * 将oMemberId乡村经纪人下的客户转移nMemberId乡村经纪人下
     *
     * @param oMemberId 原乡村经纪人id
     * @param nMemberId 变更后的乡村经纪人id
     * @return
     * @author zhouboyu
     * @Date 2020年8月28日
     */
    @ApiOperation("将oMemberId乡村经纪人下的客户转移nMemberId乡村经纪人下")
    @RequestMapping(value = "/member/change", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult cancel(Long oMemberId, Long nMemberId) {
        List<UmsMember> umsMembers = this.umsDistributionMemberService.queryMembersByDistributionId(oMemberId);
        if (umsMembers != null && !umsMembers.isEmpty()) {
            umsMembers.forEach(e -> {
                e.setAgentId(nMemberId);
                this.umsMemberMapper.updateByPrimaryKey(e);
            });
        }
        return CommonResult.success(umsMembers);
    }

    /**
     * 经纪人佣金提现列表
     *
     * @return
     * @author zhouboyu
     * @Date 2020年9月16日
     */
    @ApiOperation("经纪人佣金提现列表")
    @RequestMapping(value = "/member/withdrawal/list", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<CommonPage<UmsWithdrawalApply>> memberWithdrawalList(@CurrentUserName String userName,
                                                                             @RequestBody UmsWithdrawalApplyDto queryParam) {
        CommonResult<CommonPage<UmsWithdrawalApply>> memberWithdrawalList = null;
        try {
            memberWithdrawalList =
                    this.withdrawalApplyService.getMemberWithdrawalList(userName, queryParam, queryParam.getPageNum(), queryParam.getPageSize());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return memberWithdrawalList;
    }

    /**
     * 同意提现申请，拒绝提现申请
     *
     * @param userName
     * @param id
     * @param type
     * @param reason
     * @return
     * @author zhouboyu
     * @Date 2020年9月16日0
     */
    @ApiOperation("同意提现申请，拒绝提现申请")
    @RequestMapping(value = "/member/withdrawal/agreeOrRefuse", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult agreeOrRefuse(HttpServletRequest request,
                                      @CurrentUserName String userName,
                                      @RequestBody FilterParam param) {
        CommonResult commonResult = null;
        try {
            commonResult = this.withdrawalApplyService.agreeOrRefuse(userName, param.getId(), param.getType(), param.getReason(), HttpClient.getIpAddress(request));
        } catch (RuntimeException e) {
            e.printStackTrace();
            commonResult = CommonResult.failed(e.getMessage());

        }
        return commonResult;
    }



    /**
     * 获取该经纪人下的所有用户
     * @author 高强
     * @Date 2020年10月13日
     * @param agentId 经纪人id
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "/member/getAgentMember", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<CommonPage<UmsMember>> getMemberByAgent(@RequestParam Long agentId,
                                                                @RequestParam(required = false) String phone,
                                                                @RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer pageNum,
                                                                @RequestParam(value = "pageSize", defaultValue = "5", required = false) Integer pageSize){
        return umsDistributionMemberService.getMemberByAgent(agentId, phone, pageNum, pageSize);
    }

    /**
     * 把某个分销商下的用户转移到另一个分销商下
     * @param ids
     * @param newAgentId
     * @return
     */
    @RequestMapping(value = "/member/transferMember", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult transferMember(@RequestParam String ids, @RequestParam Long newAgentId){
        return umsDistributionMemberService.transferMember(ids,newAgentId);
    }

    /**
     * 获取经纪人库存列表
     * @author 孙晓亮
     * @date 2020年9月21日
     * @param agentId 经纪人id
     * @return
     */
    @ApiOperation("获取经纪人库存列表")
    @RequestMapping(value = "/member/getAgentSkuList",method = RequestMethod.GET)
    @ResponseBody
    public CommonResult getAgentSkuList(@RequestParam Long agentId,
                                        @RequestParam(required = false,defaultValue = "1") Integer pageNum,
                                        @RequestParam(required = false,defaultValue = "5") Integer pageSize){
        List<AgentSkuListResult>  agentSkuListResults =  umsDistributionMemberService.getAgentSkuList(agentId,pageNum,pageSize);
        return CommonResult.success( CommonPage.restPage(agentSkuListResults));
    }
}
